package com.ebupt.migu.caller.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ebupt.migu.caller.entity.RequestBean;
import com.ebupt.migu.caller.entity.ScheduleBean;
import com.ebupt.migu.caller.mapper.ScheduleMapper;
import com.ebupt.migu.caller.service.CallerHungUpMessageProducerService;
import com.ebupt.migu.common.sms.CallerHungUpMessageBean;
import com.ebupt.migu.common.sms.MegamarketRequestBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;
import java.time.Instant;
import java.util.*;

/**
 * @author liuyangyang@e-byte.com
 * @description: TODO
 * @date 2024/9/6 10:06
 */
@Slf4j
@RestController
public class CallerHungUpMessageController {

    @Autowired
    private ScheduleMapper mapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CallerHungUpMessageProducerService service;

    @Value("${server.port}")
    private String port;

    @RequestMapping("/send")
    public ResponseEntity<HashMap<String, String>> send(@RequestBody RequestBean request) {
        log.info("请求报文：{}", request);
        HashMap<String, String> map = new HashMap<>();
        try {
            if (request.getSendEndTime() < Instant.now().getEpochSecond()) {
                map.put("code", "1001");
                map.put("message", "当前时间已经超出请求中的下发截止时间，本次请求将不被下发至用户！");
                return ResponseEntity.ok(map);
            }
            ScheduleBean activity = new ScheduleBean();
            String key = "caller-hung-up-message-" + request.getActivityId();
            if (redisTemplate.hasKey(key)) {
                activity = JSON.parseObject(String.valueOf(redisTemplate.opsForValue().get(key)), ScheduleBean.class);
                log.info("Redis缓存中的活动信息：{}", activity);
            } else {
                activity = mapper.qryByStrategyId(request.getActivityId());
                log.info("数据库中的活动信息：{}", activity);
            }
            // 检查活动是否存在
            if (null == activity) {
                map.put("code", "1002");
                map.put("message", "当前活动不存在，请确认活动ID：" + request.getActivityId());
                return ResponseEntity.ok(map);
            }

            CallerHungUpMessageBean bean = getMessageBean(request, activity);
            service.sendMessage(bean);
            map.put("code", "0000");
            map.put("message", "SUCCESS");
            return ResponseEntity.ok(map);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            map.put("code", "9999");
            map.put("message", "SYSTEM ERR");
            return ResponseEntity.ok(map);
        }
    }

    @RequestMapping("/refresh-mega-market-conf")
    public void refresh() {
        service.refreshMegaMarketConf();
        Set<String> keys = redisTemplate.keys("mega-market-conf-*");
        keys.stream().forEach(key -> {
            log.info(String.valueOf(redisTemplate.opsForValue().get(key)));
        });
    }

    @RequestMapping("/test")
    public ResponseEntity<HashMap<String, String>> test(@RequestParam("activityId") String activityId, @RequestParam("msisdn") String msisdn) {
        HashMap<String, String> res = new HashMap<>();
        RestTemplate restTemplate = new RestTemplateBuilder().build();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 设置请求参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("activityId", activityId);
        requestBody.put("msisdn", msisdn);
        requestBody.put("sendEndTime", generateTenDigitTimestampPlus24Hours());
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
        // 发起 POST 请求
        String url = "http://127.0.0.1:" + port + "/caller-hung-up/send";
        log.info("通过本服务/send接口模拟下发：{}", url);
        restTemplate.postForObject(url, entity, String.class);
        res.put("status", "DONE!");
        return ResponseEntity.ok(res);
    }

    public static String generateRandomPhoneNumber() {
        Random random = new Random();
        // 生成 13x、15x、18x 等开头的手机号码
        int prefix = 130 + random.nextInt(999 - 130 + 1);
        StringBuilder phoneNumber = new StringBuilder(String.valueOf(prefix));
        for (int i = 0; i < 8; i++) {
            phoneNumber.append(random.nextInt(10));
        }
        return phoneNumber.toString();
    }

    public static long generateTenDigitTimestampPlus24Hours() {
        // 获取当前时间的秒级时间戳
        long currentTimeStamp = Instant.now().getEpochSecond();
        // 计算 24 小时后的时间戳
        long twentyFourHoursInSeconds = Duration.ofHours(24).getSeconds();
        return currentTimeStamp + twentyFourHoursInSeconds;
    }

    private static CallerHungUpMessageBean getMessageBean(RequestBean request, ScheduleBean activity) {
        CallerHungUpMessageBean bean = new CallerHungUpMessageBean();
        bean.setSendEndTime(request.getSendEndTime());
        MegamarketRequestBean megamarket = new MegamarketRequestBean();
        megamarket.setPort(Integer.valueOf(activity.getSendPort()));
        megamarket.setContent(activity.getSmsContent());
        megamarket.setStrategyId(activity.getStrategyId());
        megamarket.setTemplateId(activity.getTemplateId());
        megamarket.setMsisdn(request.getMsisdn());
        bean.setMegamarket(megamarket);
        return bean;
    }
}
